using UnityEngine;


[CreateAssetMenu(menuName = "RPG Setup/Item Data/ItemEffect/IceBlastOnTakingDamage", fileName = "Item effect data - IceBlastOnTakingDamage")]
public class ItemEffect_IceBlastOnTakingDamage : ItemEffect_DataSO
{
    [Range(0, 1)]
    [SerializeField] private float iceStormThreshould = .3f;
    [SerializeField] private float cooldown = 10f;
    [SerializeField] private float iceDamage = 10f;
    [SerializeField] private LayerMask whatIsEnemy;
    [SerializeField] private ElementalEffectData effectData;

    [Header("VFX Prefab")]
    [SerializeField] private GameObject iceBlastVFX;
    [SerializeField] private GameObject onHitVFX;
    private float lastTriggerTime = -9999;

    public override void ApplyEffect()
    {
        //判断产生冰暴条件
        //产生冰暴
        //造成敌人伤害
        bool isCooldown = Time.time < lastTriggerTime + cooldown;
        bool isThresshould = iceStormThreshould > player.playerHealth.GetCurrentHealthPercent();

        if (isCooldown == false && isThresshould)
        {
            Debug.Log("产生冰暴");
            lastTriggerTime = Time.time;
            player.player_VFX.CreateItemEffectVFX(iceBlastVFX, player.transform);
            AppayEffectToEnemy();
        }

    }
    private void AppayEffectToEnemy()
    {
        Collider2D[] enemys = Physics2D.OverlapCircleAll(player.transform.position, 1.5f, whatIsEnemy);

        foreach (var enemy in enemys)
        {
            IDamagable damagable = enemy.GetComponent<Enemy_Health>();

            if (damagable == null) continue;

            damagable.TakeDamage(0, iceDamage, ElementType.Ice, player.transform);

            enemy.GetComponent<Entity_StatHandler>()?.ApplyStatusEffect(ElementType.Ice, effectData);

            enemy.GetComponent<Entity_VFX>().CreateItemEffectVFX(onHitVFX, enemy.transform);
        }
    }
    public override void Subscribe(Player player)
    {
        base.Subscribe(player);
        player.playerHealth.OnTakeDamage += ApplyEffect;
    }

    public override void UnSubscribe()
    {
        base.UnSubscribe();
        player.playerHealth.OnTakeDamage -= ApplyEffect;
        player = null;
    }
}
